﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Xml;
using CoreLab.Oracle;
using Common.Utilities;
using Common.Utilities.Dispatcher;

namespace Workflows.Components.Entities.Providers
{
    public class SamplingWorker:IWorker
    {
        #region fields
        private Thread _WorkerThread;
        private SamplingInstruction _Instruction;
        private SamplingOutput _Output;
        private Guid _JobTicketID;
        private RunContext _Context;
        private string _WorkflowName;
        private string _ComponentName;

        /// <summary>
        /// 
        /// </summary>
        public string ComponentName
        {
            get { return _ComponentName; }
        }

        /// <summary>
        /// 
        /// </summary>
        public string WorkflowName
        {
            get { return _WorkflowName; }
        }
        #endregion

        #region IWorker Members

        public Thread WorkerThread
        {
            get { return _WorkerThread; }
        }

        public InstructionBase Instruction
        {
            get { return _Instruction; }
        }

        public ResultBase Output
        {
            get { return _Output; }
        }

        public Type ComponentType
        {
            get { return typeof(SamplingComponent); }
        }

        public RunContext Context
        {
            get { return _Context; }
            set { _Context = value; }
        }

        public void SetInstruction(Guid ticketGuid, InstructionBase request, string workflowName, string componentName)
        {
            this._JobTicketID = ticketGuid;
            this._Instruction = (SamplingInstruction)request;
            this._WorkflowName = workflowName;
            this._ComponentName = componentName;
        }

        public void SetInstruction(RunContext context, Guid ticketGuid, InstructionBase request, string workflowName, string componentName)
        {
            this._JobTicketID = ticketGuid;
            this._Instruction = (SamplingInstruction)Instruction;
            this._Context = context;
            this._WorkflowName = workflowName;
            this._ComponentName = componentName;
        }

        public void DoWork()
        {
            if (this.WorkerStartedEvent != null)
            {
                this.WorkerStartedEvent(this._JobTicketID, this, this.GetType(), this._Instruction);
            }
            this._WorkerThread = Thread.CurrentThread;
            this.SampleEntities();
        }


        public void DoWorkAsync()
        {
            if (this.WorkerStartedEvent != null)
            {
                this.WorkerStartedEvent(this._JobTicketID, this, this.GetType(), this._Instruction);
            }
            this._WorkerThread = new Thread(new ThreadStart(this.SampleEntities));
            this._WorkerThread.Start();
        }

        public void CancelWork()
        {
            if (this._WorkerThread != null && this._WorkerThread.IsAlive)
            {
                this._WorkerThread.Abort();
                if (this.WorkerCancelledEvent != null)
                {
                    this.WorkerCancelledEvent(this._JobTicketID, this.GetType(), this._Instruction);
                }
            }

        }

        public event WorkerStarted WorkerStartedEvent;
        public event WorkerFinished WorkerFinishedEvent;
        public event WorkerHasError WorkerErredEvent;
        public event WorkerCancelled WorkerCancelledEvent;
        public event WorkerStatusChanged WorkerStatusChangedEvent;

        #endregion

        #region work
        private void SampleEntities()
        {
            IDbConnection conn = null;
            if (this._Instruction.DbProvider == DataProviderType.MSSQL)
                conn = new SqlConnection(this._Instruction.ConnStr);
            else
                conn = new OracleConnection(this._Instruction.ConnStr);

            TableColumn[] cols =
                DbUtil.GetTableColumns(this._Instruction.DbProvider,
                                       this._Instruction.ConnStr,
                                       this._Instruction.SelectSql);
            Dictionary<string, SqlDbType> colDbTypes = new Dictionary<string, SqlDbType>();
            foreach(TableColumn col in cols)
            {
                colDbTypes.Add(col.ColumnName, col.DbType);
            }
            try
            {
                conn.Open();
                string sql = this._Instruction.SelectSql;
                string filterSql = string.Empty;
                if(this._Instruction.Filters !=null && this._Instruction.Filters.Count>0)
                {
                    string[] attrNames = new string[this._Instruction.Filters.Count];
                    this._Instruction.Filters.Keys.CopyTo(attrNames, 0);
                    for(int i=0;i<attrNames.Length;i++)
                    {
                        filterSql += attrNames[i] + "=" +
                                     FieldDataType.ToMssqlDataValue(colDbTypes[attrNames[i]],
                                                                    this._Instruction.Filters[attrNames[i]]);

                        if (i < attrNames.Length - 1)
                            filterSql += " and ";
                    }
                }
                string rangeFilterSql = string.Empty;
                if(this._Instruction.RangeFilters !=null && this._Instruction.RangeFilters.Count>0)
                {
                    string[] attrNames = new string[this._Instruction.RangeFilters.Count];
                    this._Instruction.RangeFilters.Keys.CopyTo(attrNames, 0);
                    for(int i=0;i<attrNames.Length;i++)
                    {
                        string attrName = attrNames[i];
                        Range<int> range = this._Instruction.RangeFilters[attrName];
                        rangeFilterSql += attrNames[i] + " between " + range.FromValue + " and " + range.ToValue;
                        if (i < attrNames.Length - 1)
                            rangeFilterSql += " and ";
                    }
                }

                sql = string.Format("select * from ({0}) as tmp", sql);
                if (filterSql.Length > 0 && rangeFilterSql.Length > 0)
                    sql += " where " + filterSql + " and " + rangeFilterSql;
                else if (filterSql.Length > 0)
                    sql += " where " + filterSql;
                else if (rangeFilterSql.Length > 0)
                    sql += " where " + rangeFilterSql;

                string sampleSql = string.Empty;
                if (this._Instruction.Method == SamplingMethod.Count)
                    sampleSql = " tablesample (" + this._Instruction.SampleSize + " rows)";
                else
                    sampleSql = " tablesample (" + this._Instruction.SampleSize + " percent)";

                sql += sampleSql;
                EntityProvider provider =
                    new EntityProvider(
                        this._Instruction.DbProvider,
                        this._Instruction.ConnStr,
                        sql,
                        this._Instruction.IDAttributeName,
                        string.Empty);
                List<int> entityIDs = provider.GetEntityIDs();

                this.SaveSamplingResult(this._Instruction.SamplingResultFilePath, entityIDs);

                this._Output = new SamplingOutput(this._Instruction.OwnerComponentID, this._JobTicketID, entityIDs.Count,
                                                  this._Instruction.SamplingResultFilePath);

                if(this.WorkerFinishedEvent !=null)
                {
                    this.WorkerFinishedEvent(this._JobTicketID, this.GetType(), this._Instruction, this._Output);
                }
            }
            catch(Exception ex)
            {
                if (this.WorkerErredEvent != null)
                    this.WorkerErredEvent(this._JobTicketID, this.GetType(), this._Instruction, ex.ToString(),true);
            }
        }

        private void SaveSamplingResult(string resultFilePath, List<int> entityIDs)
        {
            if (File.Exists(resultFilePath))
                File.Delete(resultFilePath);

            XmlDocument xDoc = new XmlDocument();
            xDoc.LoadXml("<Entities></Entities>");
            XmlNode root = xDoc.DocumentElement;
            foreach (int entityID in entityIDs)
            {
                XmlNode entityNode = XmlDataUtil.AddElement(ref xDoc, root, "Entity");
                XmlDataUtil.UpdateAttribute(ref xDoc, entityNode, "EntityID", entityID.ToString());
            }
            xDoc.Save(resultFilePath);
        }

        #endregion
    }
}
